var map;
var toolsInfo = {};  //存放工具数据
var groups = {};
var mks = [];        //存放工具信息空数组
$(function () {
    $.ajax({  //获取当前用户的基地权限
        type:"post",
        async:false,
        url:"../map/getBaseByUser",
        success:function(data){
            if(data==""||data==null){
                userBase =[{"remark":"40.1013888,121.151666","zoom":6,"id":"ecd525542ff811e899a100163e032443"}];
            }else{
                userBase = data;
                userBase[0].zoom = 14;    //自定义一个地图初始的方法级别
            }
        }
    })
    var BaseInfo = userBase[0].remark;   //截取存放在备注字段内的字符串
    var newArray =  BaseInfo.split(','); //以逗号分隔经纬度参数
    /**
     * 天地图内容
     */
    /*var normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', {
            maxZoom: 16,
            minZoom: 5
        }),
        normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', {
            maxZoom: 16,
            minZoom: 5
        }),
        imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', {
            maxZoom: 16,
            minZoom: 5
        }),
        imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', {
            maxZoom: 16,
            minZoom: 5
        });

    var normal = L.layerGroup([normalm, normala]),
        image = L.layerGroup([imgm, imga]);*/
    /**
     * 谷歌
     */
    /*var normalMap = L.tileLayer.chinaProvider('Google.Normal.Map', {
            maxZoom: 16,
            minZoom: 5
        }),
        satelliteMap = L.tileLayer.chinaProvider('Google.Satellite.Map', {
            maxZoom: 16,
            minZoom: 5
        });*/
    /**
     * 高德地图
     */
   /* var Gaode = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
        maxZoom: 16,
        minZoom: 5
    });
    var Gaodimgem = L.tileLayer.chinaProvider('GaoDe.Satellite.Map', {
        maxZoom: 16,
        minZoom: 5
    });
    var Gaodimga = L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion', {
        maxZoom: 16,
        minZoom: 5
    });
    var Gaodimage = L.layerGroup([Gaodimgem, Gaodimga]);
    var baseLayers = {
        "天地图": normal,
        "天地图影像": image,
        "谷歌地图": normalMap,
        "谷歌影像": satelliteMap,
        "高德地图": Gaode,
        "高德影像": Gaodimage
    }

    map = L.map("mapContent", {
        center: [newArray[0], newArray[1]],
        zoom: userBase[0].zoom,
        layers: [satelliteMap],
        zoomControl: false,
        doubleClickZoom: false,  //禁止双击鼠标放大
        measureControl: true,    //测量工具
    });

    L.control.layers(baseLayers, null).addTo(map);*/

    //初始化地图
    map = L.map('mapContent', {
        center: [newArray[0], newArray[1]],
        zoom: userBase[0].zoom,   //地图放大级别变量
        maxZoom: 16,
        zoomControl: false,
        doubleClickZoom: false,  //禁止双击鼠标放大
        crs: L.CRS.EPSG4326,
        measureControl: true,    //测量工具
    });

    var tmsUrl = "http://10.78.178.89:8086/geoserver/gwc/service/tms/1.0.0/leaflet%3Aleaflet_new_wuliu@EPSG%3A4326@png";
    /*右下角自定义信息*/
    var Attrib = '<div id=\'tdiv\' style="padding-right:10px;"></div> &copy <a>资产定位管理系统</a>&nbsp&nbsp&nbsp';

    /*添加底图*/
    var baseLayers = {
        影像底图:L.tileLayer(tmsUrl + '/{z}/{x}/{y}.jpg', {minZoom: 6,maxZoom: 20,attribution: Attrib,tms: true}).addTo(map)
    }

    //比例尺
    L.control.scale().addTo(map);

    //返回全图
    var zoomHome = L.Control.zoomHome({
        position: 'topright'
    });
    zoomHome.addTo(map);

    //鼠标经纬度
    var conbox = getConboxLatlng();
    //事件监听
    map.on("mousemove", function (e) {
        conbox.update(e)      //e为mousemove此事件对象
    })

    /*追溯条件弹出框内开始时间和结束时间设置*/
    laydate.skin('molv');                /* 设置时间插件的皮肤 */
    var start = {                        //开始时间
        elem: '#beginTime',              //选择ID为beginTime的input
        format: 'YYYY-MM-DD hh:mm:ss',   //自动生成的时间格式
        /*  min: laydate.now(), */ //设定最小日期为当前日期
        max: laydate.now(),              //最大日期
        istime: true,
        istoday: true, //是否显示今天
        start: laydate.now(0,"YYYY-MM-DD hh:mm:ss"),  //设置开始时间为当前时间
        choose: function(datas){
            over.min = datas;            //开始日选好后，重置结束日的最小日期
            /*over.start = datas;*/ //将结束日的初始值设定为开始日
        }
    };
    var over = {                         //结束时间
        elem: '#endTime',
        format: 'YYYY-MM-DD hh:mm:ss',
        max: laydate.now(),
        istime: true,
        istoday: true, //是否显示今天
        start: laydate.now(0,"YYYY-MM-DD hh:mm:ss"),
        choose: function(datas){
            start.max = datas;           //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(over);
    $('#beginTime').val(laydate.now(0, 'YYYY-MM-DD 00:00:00'));  //设置开始时间默认值
    $('#endTime').val(laydate.now(0, 'YYYY-MM-DD hh:mm:ss'));     //设置结束时间默认值

    /*追溯条件弹出框内表单验证*/
    $("#toolsSearchForm").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled', ':hidden'], //[':disabled', ':hidden', ':not(:visible)'] //设置隐藏组件可验证
        feedbackIcons: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            beginTime:{
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请选择开始时间'
                    }
                }
            },
            endTime:{
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请选择结束时间'
                    }
                }
            },
            no:{
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请输入工具编号'
                    }
                }
            },
            dataType: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请选择是否显示'
                    }
                }
            }
        }
    });
});

//添加鼠标经纬度
function getConboxLatlng(props) {
    var conBox = L.control({ position: 'bottomright' }); //创建右下角控件
    conBox.onAdd = function (map) {  //onAdd方法
        this._div = L.DomUtil.create('div', ''); // create a 'div'
        this.update();
        return this._div;
    };
    // method that we will use to update the control based on feature properties passed
    conBox.update = function (props) {
        if (props)
            this._div.innerHTML = '<div style="padding:10px;opacity:0.8;background:#BAC2D8;border-radius:5px;color:#12385F;font-size:12px;font-weight:bolder;">(' + deg_to_dms(props.latlng.lat) + ',' + deg_to_dms(props.latlng.lng) + ')</div>';
    };
    conBox.addTo(map);
    return conBox
}

//经纬度转换度分秒
function deg_to_dms(deg) {
    var d = Math.floor(deg);
    var minfloat = (deg - d) * 60;
    var m = Math.floor(minfloat);
    var secfloat = (minfloat - m) * 60;
    var s = Math.round(secfloat);
    if (s == 60) {
        m++;
        s = 0;
    }
    if (m == 60) {
        d++;
        m = 0;
    }
    return ("" + d + "°" + m + "'" + s + "\"");
}

/*设置底图容器自适应高度*/
autodivheight();
function autodivheight() { //自适应
    //获取浏览器窗口高度
    var winHeight = 0;
    if (window.innerHeight)
        winHeight = window.innerHeight;
    else if ((document.body) && (document.body.clientHeight))
        winHeight = document.body.clientHeight;
    //通过深入Document内部对body进行检测，获取浏览器窗口高度
    if (document.documentElement && document.documentElement.clientHeight)
        winHeight = document.documentElement.clientHeight;
    //自适应为浏览器窗口的高度
    document.getElementById("mapContent").style.height = winHeight - 10 + "px";
}
window.onresize = autodivheight; //浏览器窗口发生变化时同时变化DIV高度

/*判断浏览器版本*/
var browser = navigator.appName;
var b_version = navigator.appVersion;
var version = b_version.split(";");
var trim_Version = version[1].replace(/[ ]/g, "");
if (browser == "Microsoft Internet Explorer" && (trim_Version == "MSIE6.0" || trim_Version == "MSIE7.0" || trim_Version == "MSIE8.0")) {
    alert("浏览器版本过低");
}

/*划分区域*/
var vector = {};
(function(res){
    res.loadVector = function(){
        $.ajax({
            url:"../map/getVectorGraph",
            dataType:"json",
            success:function(data){
                console.log(data);
                res.constructorGeoJson(data);  //画面
            }
        });
    };
    res.constructorGeoJson=function(data){
        var polygonArray = new Array();//新数组
        var roundArray = new Array();
        for ( var i in data) {
            if(data[i].graphType=="3"){
                polygonArray.push(res.constructorPolygon(data[i]));//将面数据添加到polygonArray数组中
                /* console.log(polygonArray);*/
            };
            if(data[i].graphType=="4"){
                roundArray.push(res.constructorRound(data[i]));
            }
        }
        //console.log(polygonArray);
        L.geoJSON(polygonArray,{
            style:function(feature){
                var style = {};
                style.color = feature.properties.color;
                style.fillColor = feature.properties.fillColor;
                style.fillOpacity = 1;
                return style;
            }/*,
            onEachFeature:function(feature, layer){//添加事件和弹出框
                layer.feature = feature;
                layer.on("click",res.cliceTest);
            }*/
        }).addTo(map);
        //创建面的geojson绘画
        res.canvasGeoJson(polygonArray,3);
        res.canvasGeoJson(roundArray,4);
    };
    //leaflet原生的geojson绘画方法 type:3面，4圆
    res.canvasGeoJson=function(array,type){
        if (type==3) {
            L.geoJSON(array,{
                style:function(feature){
                    var style = {};
                    style.color = feature.properties.color;
                    style.fillColor = feature.properties.fillColor;
                    style.fillOpacity = 1;
                    return style;
                }/*,
                onEachFeature:function(feature, layer){
                    layer.feature = feature;
                    //绑定面的点击事件
                    if(feature.properties.modelType!=undefined&&feature.properties.modelType!=""){
                        layer.on("dblclick",function(){
                            //点击面的事件
                            //判断点击的是什么模型，根据模型
                            if(feature.properties.modelType=="kf"){
                                $("#kf_dialog").find("#modelId").val(feature.properties.id);
                                $("#kf_dialog").dialog("open");
                            }
                            if(feature.properties.modelType=="lc"){
                                $("#lc_dialog").find("#modelId").val(feature.properties.id);
                                $("#lc_dialog").dialog("open");
                            }
                            if(feature.properties.modelType=="bgcs"){
                                $("#bgcs_dialog").find("#modelId").val(feature.properties.id);
                                $("#bgcs_dialog").dialog("open");
                            }
                            if(feature.properties.modelType=="mt"){
                                $("#mt_dialog").find("#modelId").val(feature.properties.id);
                                $("#mt_dialog").dialog("open");
                            }
                        });
                    }
                    if(feature.properties.showName==0){
                        var popup = L.popup().setLatLng(feature.properties.latlng).setContent("<span>"+feature.properties.name+"</span>");
                        layer.on("mouseover",function(e){
                            //移上的事件
                            map.openPopup(popup);
                        });
                        layer.on("mouseout",function(e){
                            //移出的事件
                            map.closePopup(popup);
                        });
                    }
                }*/
            }).addTo(map);
        }else{
            L.geoJSON(array,{
                pointToLayer:function(feature, latlng){
                    return L.circle(latlng,{
                        radius: feature.properties.radius,
                        color: feature.properties.color,
                        fill: true, fillColor: feature.properties.fillColor,
                        fillOpacity: 1});
                }/*,
                onEachFeature:function(feature, layer){
                    //绑定面的点击事件
                    if(feature.properties.modelType!=undefined&&feature.properties.modelType!=""){
                        layer.on("click",function(){
                            //点击面的事件
                        });
                    }
                }*/
            }).addTo(map);
        }
    };
    //构造圆的GeoJson数据
    res.constructorRound=function(data){
        //设置基本属性
        var properties = {};
        properties.id=data.id;
        properties.graphType=data.graphType;
        properties.name=data.name;
        properties.radius=data.radius;
        properties.yradius=data.radius;
        properties.color=data.color;
        properties.fillColor=data.fillColor;
        properties.weight=data.width;
        properties.isHt = false;
        properties.latlng = [data.reservedLat,data.reservedLog];
        properties.showName = data.showName;
        properties.modelType = data.modelType;

        var polyline = {};
        //构造线的坐标数据
        var geometry = {};
        var coordinates = [parseFloat(data.reservedLog),parseFloat(data.reservedLat)];
        geometry.coordinates = coordinates;
        geometry.type = "Point";
        polyline.geometry = geometry;
        polyline.type = "Feature";
        polyline.properties = properties;
        return polyline;
    };
    //构造多边形GeoJson数据
    res.constructorPolygon=function(data){
        //设置基本属性
        var properties = {};
        properties.id=data.id;
        properties.graphType=data.graphType;
        properties.name=data.name;
        properties.radius=data.radius;
        properties.yradius=data.radius;
        properties.color=data.color;
        properties.fillColor=data.fillColor;
        properties.weight=data.width;
        properties.latlng = [data.reservedLat,data.reservedLog];
        properties.modelType = data.modelType;
        properties.showName = data.showName;
        properties.isHt = false;
        var geoJsonData = {};
        geoJsonData.type="Feature";
        geoJsonData.properties = properties;

        //创建图形所用的经纬度数组数据
        var coordinates = new Array();
        var polygs = new Array();
        for ( var pol in data.vectorGraphPoints) {
            var polyg = [parseFloat(data.vectorGraphPoints[pol].log),parseFloat(data.vectorGraphPoints[pol].lat)];
            polygs.push(polyg);
        }
        coordinates.push(polygs);
        //创建线面坐标信息
        var geometry = {};
        geometry.coordinates = coordinates;
        geometry.type = "Polygon";
        geoJsonData.geometry = geometry;
        return geoJsonData;
    };

    res.constructionData=function(data){
        //构造geoJsonText的外层结构
        var textArray = new Array();
        var geoJsonText = {};
        geoJsonText.type = "FeatureCollection";
        //构造geoJsonPoint的外层结构
        var pointArray = new Array();
        var geoJsonPoint = {};
        geoJsonPoint.type = "FeatureCollection";
        //构造geoJsonLineString的外层结构
        var lineStringArray = new Array();
        var geoJsonLineString = {};
        geoJsonLineString.type = "FeatureCollection";
        //构造geoJsonMultiPolyg的外层结构
        var multiPolygArray = new Array();
        var geoJsonMultiPolyg = {};
        geoJsonMultiPolyg.type = "FeatureCollection";
        for ( var i in data) {
            if(data[i].graphType=="1"){
                //构造文本数据
                textArray.push(res.constrText(data[i]));
            };
            if(data[i].graphType=="2"){
                lineStringArray.push(res.constrLineString(data[i]));
            };
            if(data[i].graphType=="3"){
                multiPolygArray.push(res.constrMultiPolyg(data[i]));
            };
            if(data[i].graphType=="4"){
                pointArray.push(res.constrPoint(data[i]));
            };
        }
        geoJsonPoint.features = pointArray;
        geoJsonLineString.features = lineStringArray;
        geoJsonMultiPolyg.features = multiPolygArray;
        geoJsonText.features = textArray;
        res.loadPolyg(geoJsonLineString);
        res.loadPolyg(geoJsonMultiPolyg);
        res.loadPolyg(geoJsonPoint);
        res.loadPolyg(geoJsonText);
    };

    //构造文本数据
    res.constrText=function(data){
        //设置基本属性
        var properties = {};
        properties.id=data.id;
        properties.graphType=data.graphType;
        properties.name=data.name;
        properties.radius=data.radius;
        properties.yradius=data.radius;
        properties.color=data.color;
        properties.fColor=data.fillColor;
        properties.width=data.width;
        properties.isHt = false;

        var polyline = {};
        //构造线的坐标数据
        var geometry = {};
        var coordinates = [parseFloat(data.reservedLog),parseFloat(data.reservedLat)];
        geometry.coordinates = coordinates;
        geometry.type = "Text";
        polyline.geometry = geometry;
        polyline.type = "Feature";
        polyline.properties = properties;
        return polyline;
    };
    //构造点型数据
    res.constrPoint=function(data){
        //设置基本属性
        var properties = {};
        properties.id=data.id;
        properties.graphType=data.graphType;
        properties.name=data.name;
        properties.radius=data.radius;
        properties.yradius=data.radius;
        properties.color=data.color;
        properties.fColor=data.fillColor;
        properties.width=data.width;
        properties.isHt = false;

        var polyline = {};
        //构造线的坐标数据
        var geometry = {};
        var coordinates = [parseFloat(data.reservedLog),parseFloat(data.reservedLat)];
        geometry.coordinates = coordinates;
        geometry.type = "Point";
        polyline.geometry = geometry;
        polyline.type = "Feature";
        polyline.properties = properties;
        return polyline;

    };
    //构造线型数据
    res.constrLineString=function(data){

        var polyline = {};
        //设置基本属性
        var properties = {};
        properties.id=data.id;
        properties.graphType=data.graphType;
        properties.name=data.name;
        properties.radius=data.radius;
        properties.color=data.color;
        properties.fColor=data.fillColor;
        properties.width=data.width;

        polyline.type = "Feature";
        //构造线的坐标数据
        var geometry = {};
        var coordinates = new Array();
        for ( var pol in data.vectorGraphPoints) {
            var polyg = [parseFloat(data.vectorGraphPoints[pol].log),parseFloat(data.vectorGraphPoints[pol].lat)];
            coordinates.push(polyg);
        }

        geometry.coordinates = coordinates;
        geometry.type = "LineString";
        polyline.geometry = geometry;
        polyline.properties = properties;
        return polyline;
    };
    //构造多边形数据
    res.constrMultiPolyg=function(data){
        var conData = {};
        conData.type="Feature";
        //设置基本属性
        var properties = {};
        properties.id=data.id;
        properties.graphType=data.graphType;
        properties.name=data.name;
        properties.radius=data.radius;
        properties.color=data.color;
        properties.fColor=data.fillColor;
        properties.width=data.width;

        conData.properties = properties;

        //创建图形所用的经纬度数组数据
        var coordinates = new Array();
        var polygs = new Array();
        for ( var pol in data.vectorGraphPoints) {
            var polyg = [parseFloat(data.vectorGraphPoints[pol].log),parseFloat(data.vectorGraphPoints[pol].lat)];
            polygs.push(polyg);
        }
        coordinates.push(polygs);
        //创建线面坐标信息
        var geometry = {};
        geometry.coordinates = coordinates;
        geometry.type = "Polygon";
        conData.geometry = geometry;
        return conData;
    };
    res.loadPolyg=function(geoJson){
        console.log(geoJson)
        var canvasLayer = new L.CanvasGeojsonLayer({
            onMouseOver :function(features){
                //处理鼠标悬停事件
            },
            onMouseOut  : function(features){
                //处理mouseout事件
            },
            onClick  : function(features){
                //处理鼠标点击事件
            }
        });

        canvasLayer.addTo(map);
        var data = L.CanvasFeatureFactory(geoJson);
        canvasLayer.addCanvasFeatures(data);
        canvasLayer.render();
    };
})(vector);

/*搜索按钮点击事件弹出框*/
function searchToggle(obj, evt){
    /*closest() 方法获得匹配选择器的第一个祖先元素，从当前元素开始沿 DOM 树向上。*/
    var container = $(obj).closest('.search-wrapper');
    if(!container.hasClass('active')){               //搜索框最外层父元素是否有active类，用于样式控制搜索框显示或隐藏
        container.addClass('active');                //搜索按钮点击时添加active类，用于显示搜索弹框
        $(".searchInfo").css("display","block");     //搜索框内容显示
        $(".search-icon").css("display","none");     //地图左上角搜索按钮隐藏
        evt.preventDefault();
    } else if(container.hasClass('active') && $(obj).closest('.input-holder').length == 0){
        container.removeClass('active');             //搜索按钮点击时移除active类，用于隐藏搜索弹框
        $(".searchInfo").css("display","none");      //搜索框内容隐藏
        $(".search-icon").css("display","block");    //地图左上角搜索按钮显示
    }
}

/*搜索弹出框内查询按钮点击事件*/
function subSearch(){
    var $formlist = $('#toolsSearchForm');
    var data = $formlist.data('bootstrapValidator');
    if (data) {
        // 修复记忆的组件不验证
        data.validate();
        if (!data.isValid()) {
            return false;
        }
    }
    var searchData = {};
    searchData.beginTime=$("#beginTime").val();
    searchData.endTime = $("#endTime").val();
    searchData.toolNo=$("#no").val();

    cleratoolHistory()  //调用前先清除一下地图上现有的历史轨迹

    toolsHistoryLocus(searchData);  //调用历史轨迹方法

    searchToggle($("#boxHide"), event); //调用隐藏搜索条件方法

    var isShow = $("#isShow").val();
    if(isShow=="bxs"){  //不显示
        $("#toolInfoDialog").modal("hide");
    }else{              //显示

        $("#toolInfoDialog").modal("show");
        loadHistoryData(searchData);  //调用显示列表方法
    }

}

/*工具历史轨迹*/
var polylineArray = new Array();
var beginBzArray = new Array();
function toolsHistoryLocus(searchData){
    cleratoolHistory();     //调用历史轨迹查询时先清除上传的轨迹
    $.ajax({
        url:"../map/getToolTrajectoryList",
        type:"post",
        data:searchData,
        success:function(data){
            if(data.code==0){  //存在历史数据
                var hisInfo = data.result;
                if (hisInfo.length>0) {
                    var latlngs = [];
                    for (var i = 0; i < hisInfo.length; i++) {
                        var beginBz = {};
                        if(i==(hisInfo.length-1)){   //终点图标
                            var endIcon = L.icon({iconUrl: '../static/img/zd.png',iconSize: [30, 30],iconAnchor: [15, 30],});
                            beginBz = L.marker([hisInfo[i].latitude,hisInfo[i].longitude],{
                                icon:endIcon,
                                title:"时间："+new Date(hisInfo[i].collectionTime).Format("yyyy-MM-dd hh:mm:ss")+"  纬度："+hisInfo[i].latitude+"  经度："+hisInfo[i].longitude
                            });
                        }else{
                            if(i==0){  //起点图标
                                var beginIcon = L.icon({iconUrl: '../static/img/qd.png',iconSize: [30, 30],iconAnchor: [15, 28],});
                                beginBz = L.marker([hisInfo[i].latitude,hisInfo[i].longitude],{
                                    icon:beginIcon,
                                    title:"时间："+new Date(hisInfo[i].collectionTime).Format("yyyy-MM-dd hh:mm:ss")+"  纬度："+hisInfo[i].latitude+"  经度："+hisInfo[i].longitude
                                });
                            }else{  //起点和终点间各点位图标
                                var myIcon = L.icon({iconUrl: '../static/img/lsjd.png',iconSize: [12, 12],iconAnchor: [6, 6],});
                                beginBz = L.marker([hisInfo[i].latitude,hisInfo[i].longitude],{
                                    icon:myIcon,
                                    title:"时间："+new Date(hisInfo[i].collectionTime).Format("yyyy-MM-dd hh:mm:ss")+"  纬度："+hisInfo[i].latitude+"  经度："+hisInfo[i].longitude
                                });
                            }
                        }
                        map.addLayer(beginBz);
                        beginBzArray.push(beginBz);
                        var latlng = new L.LatLng(hisInfo[i].latitude,hisInfo[i].longitude);
                        latlngs.push(latlng);
                    }
                    var polylineOptions = {
                        color: 'blue',
                        weight: 2,
                        dashArray: '5,5',
                        opacity: 0.9
                    };
                    var polyline = new L.Polyline(latlngs, polylineOptions);
                    console.log(polyline);
                    map.addLayer(polyline);
                    polylineArray.push(polyline);
                    /*$("#toolInfoDialog").modal("hide");*/   //关闭弹出框
                }
            }else{   //无历史数据
                layer.msg("暂无历史轨迹数据");
            }
        }
    });
}

/*清除历史轨迹*/
function cleratoolHistory(){
    for ( var int = 0; int < polylineArray.length; int++) {
        map.removeLayer(polylineArray[int]);
    }
    for ( var int = 0; int < beginBzArray.length; int++) {
        map.removeLayer(beginBzArray[int]);
    }
}

function loadHistoryData(searchData){
    $('#historyTable').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
    var dataInfo = "";
    /* 初始化历史轨迹表格数据 */
    $('#historyTable').bootstrapTable({
        method: 'POST',
        url:"../map/getToolTrajectoryList",   /* 调用后台接口加载数据 */
        queryParamsType:'',
        queryParams:function (params) {
            return {  /*参数*/
                beginTime:searchData.beginTime,
                endTime:searchData.endTime,
                toolNo:searchData.toolNo
            };
        },
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",
        cache: false,     // 不缓存
        striped: true,    // 隔行加亮
        pagination: true, //是否显示分页
        singleSelect:true, //单选
        pageSize: 10,
        pageNumber: 1,     //初始化加载第一页，默认第一页
        pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
        showColumns: true,
        showRefresh: true,  //是否显示刷新按钮
        clickToSelect: true,  //是否启用点击选中行
        /*sidePagination: "server",*/
        columns: [
            {field: '',title: '序号',width: 20,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
            {field:"collectionTime",title:"轨迹时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {return new Date(value).Format("yyyy-MM-dd hh:mm:ss")}},
            {field:"longitude",title:"经度",align:"center",valign:"middle",sortable:"true"},
            {field:"latitude",title:"纬度",align:"center",valign:"middle",sortable:"true"}
        ],
        formatLoadingMessage: function () {
            return "请稍等，正在加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        responseHandler: function(res) {
            var total,rows,tool;
            if(res.code==0){
                if(res.result.length>0){
                    total = res.result.length;
                    rows = res.result;
                    tool = res.tool;
                }
            }else{
                rows = new Array();
                tool = res.tool;
            }
            return {
                data:rows,  //数据
                "tool":tool
            };

        },
        onLoadSuccess:function(data){  //当所有数据被加载时触发
            if(data.tool==undefined){
                $("#toolDetailInfo").html("<p style='text-align: center;margin: 10px 0;'>暂无该工具信息</p>");
            }else{
                var  dataInfo = data.tool;
                var html = "";
                /*生产日期时间格式转换*/
                var dataTime = new Date(dataInfo.manufactureDate).Format("yyyy-MM-dd");
                html+="<table class='table table-bordered toolTable'>" +
                    "<tr><td class='titleCol'>工具类型</td>"+"<td>"+formatter(dataInfo.typeName)+"</td><td class='titleCol'>工具名称</td>"+"<td>"+formatter(dataInfo.toolName)+"</td></tr>"+
                    "<tr><td class='titleCol'>工具编号</td>"+"<td>"+formatter(dataInfo.no)+"</td><td class='titleCol'>规格尺寸</td>"+"<td>"+formatter(dataInfo.dimensionName)+"</td></tr>"+
                    "<tr><td class='titleCol'>自重</td>"+"<td>"+formatter(dataInfo.deadWeight)+"</td><td class='titleCol'>安全载荷</td>"+"<td>"+formatter(dataInfo.safeLoad)+"</td></tr>"+
                    "<tr><td class='titleCol'>生产日期</td>"+"<td>"+formatter(dataTime)+"</td><td class='titleCol'>状态</td>"+"<td>"+formatter(dataInfo.statusStr)+"</td></tr>"+
                    "<tr><td class='titleCol'>归属地</td>"+"<td colspan='3'>"+formatter(dataInfo.baseName)+"</td></tr>"+
                    "</table>"
                $("#toolDetailInfo").html(html);
            }
        }
    });
/**/
    $(window).resize(function (e, value, row, index) {
        $('#historyTable').bootstrapTable('resetView');
    });
}

function formatter(value){
    if(value==null){
        return "";
    }else{
        return value;
    }
}
// 对Date的扩展，将 Date 转化为指定格式的String
Date.prototype.Format = function (fmt) { //author: zhengsh 2016-9-5
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}